package com.cskaoyan.service.admin.marketmanage;


import com.cskaoyan.dao.polularize.MarketDao;
import com.cskaoyan.dao.wx.WxOrderDao;
import com.cskaoyan.model.BaseParam;
import com.cskaoyan.model.admin.marketbeans.bo.*;
import com.cskaoyan.model.admin.marketbeans.pojo.*;
import com.cskaoyan.model.admin.marketbeans.vo.*;
import com.cskaoyan.model.admin.marketbeans.vo.Regionvo.ProvinceDto;
import com.cskaoyan.model.admin.marketbeans.vo.Regionvo.RegionBeanVo;
import com.cskaoyan.model.admin.marketbeans.vo.brandmsgvo.BrandMsgDto;
import com.cskaoyan.model.admin.marketbeans.vo.brandmsgvo.BrandMsgVo;
import com.cskaoyan.model.admin.marketbeans.bo.OrderShipBo;
import com.cskaoyan.utils.RedisUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import java.util.List;

/**
 * @package: com.cskaoyan.service
 * @Description: 商场管理
 * @author: 北青
 * @date: 2022/1/6 21:48
 */
@Service
@Transactional
public class MarketServiceImpl implements com.cskaoyan.service.marketmanage.MarketService {

    @Autowired
    MarketDao marketDao;

    @Autowired
    RedisUtils redisUtils;

    @Autowired
    WxOrderDao wxOrderDao;

    /**
     * 售后信息模块获取售后信息
     *
     * @param marketAftersaleListBO
     * @return
     */
    @Override
    public MarketAftersaleListVo getMarketAftersaleListInfo(MarketAftersaleListBo marketAftersaleListBO) {
        Integer page = marketAftersaleListBO.getPage();//页码
        Integer limit = marketAftersaleListBO.getLimit();//数据量
        String sort = marketAftersaleListBO.getSort();//排序列
        String order = marketAftersaleListBO.getOrder();//desc\asc
        //分页插件 PageHelper，辅助我们做分页以及分页信息的获得
        PageHelper.startPage(page, limit);

        //在数据库中查询售后信息
        List<MarketAftersale> marketAftersaleListInfo = marketDao.getMarketAftersaleListInfo(marketAftersaleListBO);

        PageInfo<MarketAftersale> pageInfo = new PageInfo<>(marketAftersaleListInfo);

        long total = pageInfo.getTotal();
        int pages = pageInfo.getPages();

        MarketAftersaleListVo marketAftersaleListVO = MarketAftersaleListVo.addData(total, pages, limit, page, marketAftersaleListInfo);

        return marketAftersaleListVO;
    }

    /**
     * 售后信息处理——通过
     *
     * @param marketAftersale: 选中的售后信息
     */
    @Override
    public void recept(MarketAftersale marketAftersale) {
        Integer status = 2; //通过后的售后状态
        changeAftersaleStatus(marketAftersale, status);
        Integer orderId = marketAftersale.getOrderId();
        //同时修改订单中的状态
        marketDao.updateOrderAfterasleStatus(status ,orderId);
    }

    /**
     * 修改售后信息状态的具体方法
     *
     * @param marketAftersale: 要修改的售后信息详情
     * @param status:          修改后的状态码
     */
    private void changeAftersaleStatus(MarketAftersale marketAftersale, Integer status) {
        Integer id = marketAftersale.getId(); //售后信息id
        Integer[] ids = {id};
        marketDao.changeAftersaleStatus(ids, status);
    }

    /**
     * 售后信息处理——拒绝
     *
     * @param marketAftersale: 选中的售后信息
     */
    @Override
    public void reject(MarketAftersale marketAftersale) {
        Integer status = 4; //通过后的售后状态
        changeAftersaleStatus(marketAftersale, status);
        Integer orderId = marketAftersale.getOrderId();
        //同时修改订单中的状态
        marketDao.updateOrderAfterasleStatus(status ,orderId);
    }

    /**
     * 售后信息处理——批量通过
     *
     * @param ids: 要批量处理的售后信息id
     */
    @Override
    public void batchRecept(Integer[] ids) {
        Integer status = 2; //通过后的售后状态
        marketDao.changeAftersaleStatus(ids, status);
        //获取订单ID
        List<Integer> orderIds = marketDao.getOrderIdsByAftersaleId(ids);
        for (Integer orderId : orderIds) {
            //同时修改订单中的状态
            marketDao.updateOrderAfterasleStatus(status ,orderId);
        }
    }

    /**
     * 售后信息处理——批量拒绝
     *
     * @param ids: 要批量处理的售后信息id
     */
    @Override
    public void batchReject(Integer[] ids) {
        Integer status = 4; //通过后的售后状态
        marketDao.changeAftersaleStatus(ids, status);
        //获取订单ID
        List<Integer> orderIds = marketDao.getOrderIdsByAftersaleId(ids);
        for (Integer orderId : orderIds) {
            //同时修改订单中的状态
            marketDao.updateOrderAfterasleStatus(status ,orderId);
        }
    }

    /**
     * 售后信息处理——退款
     *
     * @param marketAftersale
     */
    @Override
    public void refund(MarketAftersale marketAftersale) {
        Integer status = 3; //退款后的售后信息状态
        Integer orderStatus = 203; //退款后的订单状态
        changeAftersaleStatus(marketAftersale, status);
        //获得订单id
        Integer orderId = marketAftersale.getOrderId();
        //修改订单状态
        changeOrderStatus(orderId, orderStatus);
        //更新订单信息
        MarketOrder marketOrder = new MarketOrder();
        marketOrder.setId(orderId);
        int type = marketAftersale.getType();
        String typeDes = null;
        if (type == 0) {//0是未收货退款，1是已收货（无需退货）退款，2用户退货退款
            typeDes = "未收货退款";
        } else if (type == 1) {
            typeDes = "已收货（无需退货）退款";
        } else {
            typeDes = "退货退款";
        }
        marketOrder.setRefundType(typeDes);
        marketOrder.setRefundContent(marketAftersale.getComment());
        marketOrder.setRefundTime(new Date(System.currentTimeMillis()));
        marketOrder.setUpdateTime(new Date(System.currentTimeMillis()));
        wxOrderDao.updateOrderValues(marketOrder);
        //同时修改订单中的状态
        marketDao.updateOrderAfterasleStatus(status ,orderId);
    }

    /**
     * 根据订单ID修改订单状态
     *
     * @param orderId
     * @param orderStatus
     */
    private void changeOrderStatus(Integer orderId, Integer orderStatus) {
        marketDao.changeOrderStatus(orderId, orderStatus);
    }

    /**
     * 通用问题——显示问题信息
     *
     * @param question
     * @param baseParam
     * @return
     */
    @Override
    public MarketIssueListVo getIssueListInfo(String question, BaseParam baseParam) {
        Integer page = baseParam.getPage();
        Integer limit = baseParam.getLimit();
        //分页
        PageHelper.startPage(page, limit);

        //在数据库中查询通用问题信息
        List<MarketIssue> issueListInfo = marketDao.getIssueListInfo(question, baseParam.getSort(), baseParam.getOrder());

        PageInfo<MarketIssue> pageInfo = new PageInfo<>();
        long total = pageInfo.getTotal();
        int pages = pageInfo.getPages();

        MarketIssueListVo marketIssueListVo = MarketIssueListVo.addData(total, pages, limit, page, issueListInfo);
        return marketIssueListVo;
    }

    /**
     * 通用问题模块——新增问题
     *
     * @param marketIssue
     */
    @Override
    public void createIssue(MarketIssue marketIssue) {
        marketDao.createIssue(marketIssue);
    }

    /**
     * 通用问题模块——编辑修改问题
     *
     * @param marketIssue
     */
    @Override
    public void updateIssue(MarketIssue marketIssue) {
        marketDao.updateIssue(marketIssue);
    }

    /**
     * 通用问题模块——删除问题信息
     *
     * @param marketIssue
     */
    @Override
    public void deleteIssue(MarketIssue marketIssue) {
        marketDao.updateIssue(marketIssue);
    }

    /**
     * 商城——关键词——关键词信息显示
     *
     * @param marketKeywordListBo
     * @return
     */
    @Override
    public MarketKeywordListVo getMarketKeywordInfo(MarketKeywordListBo marketKeywordListBo) {
        //获取分页信息
        Integer page = marketKeywordListBo.getPage();
        Integer limit = marketKeywordListBo.getLimit();
        //分页
        PageHelper.startPage(page, limit);
        //查询数据库信息
        List<MarketKeyword> marketKeywordInfo = marketDao.getMarketKeywordInfo(marketKeywordListBo);

        PageInfo<MarketKeyword> pageInfo = new PageInfo<>();
        long total = pageInfo.getTotal();
        int pages = pageInfo.getPages();

        MarketKeywordListVo marketKeywordListVo = MarketKeywordListVo.addData(total, pages, limit, page, marketKeywordInfo);
        return marketKeywordListVo;
    }

    /**
     * 商城——关键词——添加关键词信息
     *
     * @param marketKeyword
     */
    @Override
    public void createKeyword(MarketKeyword marketKeyword) {
        if (marketKeyword.getUrl() == null) {
            marketKeyword.setUrl("");
        }
        if (marketKeyword.getIsHot() == null) {
            marketKeyword.setIsHot(false);
        }
        if (marketKeyword.getIsDefault() == null) {
            marketKeyword.setIsDefault(false);
        }
        marketDao.createKeyword(marketKeyword);
    }

    /**
     * 商城——关键词——修改关键词信息
     *
     * @param marketKeyword
     */
    @Override
    public void updateKeyword(MarketKeyword marketKeyword) {
        marketDao.updateKeyword(marketKeyword);
    }

    /**
     * @createTime: 2022/1/7 20:53
     * @author: Dragon
     * @description: 商城管理模块-行政区域查询全部信息service
     */
    @Override
    public RegionBeanVo getRegionList() {

        List<ProvinceDto> allRegionList = marketDao.getAllRegionList();
        RegionBeanVo regionBeanVo = new RegionBeanVo(31, 1, 31, 1, allRegionList);
        return regionBeanVo;

//        if (redisUtils.hasKey("regionList")) {
//            return (RegionBeanVo) redisUtils.getStringStructOfValue("regionList");
//        } else {
//            // redis缓存不命中访问数据库
//            List<ProvinceDto> allRegionList = marketDao.getAllRegionList();
//            RegionBeanVo regionBeanVo = new RegionBeanVo(31, 1, 31, 1, allRegionList);
//            redisUtils.setStringStructOfValue("regionList", regionBeanVo);
//            return regionBeanVo;
//        }
    }


    /**
     * @createTime: 2022/1/7 20:53
     * @author: Dragon
     * @description: 商城管理模块-品牌制造商查询全部信息service
     */
    @Override
    public BrandMsgVo getBrandList(BaseParam baseParam, String id, String name) {
        Integer page = baseParam.getPage();
        Integer limit = baseParam.getLimit();
        PageHelper.startPage(page, limit);

        List<BrandMsgDto> brandMsgList = marketDao.getAllBrandMsgList(baseParam, id, name);

        PageInfo<BrandMsgDto> pageInfo = new PageInfo<>(brandMsgList);
        int pages = pageInfo.getPages();
        long total = pageInfo.getTotal();

        return new BrandMsgVo((int) total, pages, limit, page, brandMsgList);
    }


    /**
     * @createTime: 2022/1/7 20:53
     * @author: Dragon
     * @description: 商城管理模块-品牌制造商-添加品牌service
     */
    @Override
    public BrandAddVo addNewBrand(AddBrandBo addBrandBo) {
        //更新add时间
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd : hh:mm:ss");
        addBrandBo.setAddTime(dateFormat.format(date));
        addBrandBo.setUpdateTime(dateFormat.format(date));

        //插入信息到数据库
        marketDao.createNewBrand(addBrandBo);

        //获取返回的id值
        Integer id = addBrandBo.getId();

        BrandAddVo brandAddVo = new BrandAddVo(id, addBrandBo.getName(), addBrandBo.getDesc(), addBrandBo.getPicUrl(), addBrandBo.getFloorPrice(), addBrandBo.getAddTime(), addBrandBo.getUpdateTime());
        return brandAddVo;
    }

    /**
     * 商城——订单管理——订单信息显示
     *
     * @param marketOrderListBo
     * @return
     */
    @Override
    public MarketOrderInfoVo getOrderListInfo(MarketOrderListBo marketOrderListBo) {
        //获取分页信息
        Integer page = marketOrderListBo.getPage();
        Integer limit = marketOrderListBo.getLimit();
        //分页
        PageHelper.startPage(page, limit);
        //查询数据库信息
        List<MarketOrder> list = marketDao.getOrderListInfo(marketOrderListBo);

        PageInfo<MarketOrder> pageInfo = new PageInfo<>(list);
        long total = pageInfo.getTotal();
        int pages = pageInfo.getPages();

        MarketOrderInfoVo marketOrderInfoVo = MarketOrderInfoVo.addData(total, pages, limit, page, list);
        return marketOrderInfoVo;
    }

    @Override
    public UpdateBrand renewBrand(UpdateBrand updateBrand) {
        //更新update时间
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd : hh:mm:ss");
        updateBrand.setUpdateTime(dateFormat.format(date));

        marketDao.updateBrand(updateBrand);
        return updateBrand;
    }

    @Override
    public int removeBrand(Integer id) {
        int i = marketDao.deleteBrand(id);
        return i;
    }

    @Override
    public CategoryListVo getAllCategoryMsg() {
        int i = marketDao.selectCountCategory();

        List<CategoryListDto> DtoList = marketDao.selectAllCategory();

        return new CategoryListVo(i, 1, i, 1, DtoList);
    }

    @Override
    public GetLevelFirstCategory getLevel1CategoryMsg() {
        int i = marketDao.selectCountCategory();
        List<GetLevelFirstChirldCategoryDto> categoryDtoList = marketDao.selectLevel1Category();

        return new GetLevelFirstCategory(i, 1, i, 1, categoryDtoList);
    }

    @Override
    public AddCategory addCategory(AddCategory addCategory) {
        //更新add时间
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd : hh:mm:ss");
        addCategory.setAddTime(dateFormat.format(date));
        addCategory.setUpdateTime(dateFormat.format(date));

        int i = marketDao.createCategory(addCategory);

        return new AddCategory(addCategory.getId(), addCategory.getName(), addCategory.getKeywords(), addCategory.getDesc(), addCategory.getPid(),
                addCategory.getIconUrl(), addCategory.getPicUrl(), addCategory.getLevel(), addCategory.getAddTime(), addCategory.getUpdateTime());

    }

    @Override
    public int deleteCategory(Integer id) {
        int i = marketDao.deleteCategory(id);
        return i;
    }

    @Override
    public void updateCategory(UpdateCategoryBo updateCategoryBo) {
        if (updateCategoryBo.getPid() != null) {
            //二级变一级
 /*           if (updateCategoryBo.getLevel().equals("L2") && updateCategoryBo.getPid().equals(0)) {
                updateCategoryBo.setLevel("L1");
                System.out.println(updateCategoryBo.getLevel());
            }*/
          /*  //一级变二级，pid部分
            if (updateCategoryBo.getLevel().equals("L1")) {
                updateCategoryBo.setLevel("L2");
            }*/
            //二级变二级、二级变一级
            marketDao.updateOutCategory(updateCategoryBo);
            //一级变二级,children部分

         /*   if (updateCategoryBo.getChildren() != null && !updateCategoryBo.getChildren().equals("")) {
            if (!updateCategoryBo.getChildren().isEmpty()) {

                List<UpdateCategoryChilrenDto> children = updateCategoryBo.getChildren();
                ArrayList<Integer> list = new ArrayList<>();
                for (UpdateCategoryChilrenDto child : children) {
                    list.add(child.getId());
                }
                marketDao.updateInnerCaregory(list, updateCategoryBo.getPid());
            }*/
            System.out.println(updateCategoryBo.getChildren());
            if (!updateCategoryBo.getChildren().isEmpty()) {
                List<UpdateCategoryChilrenDto> children = updateCategoryBo.getChildren();
                ArrayList<Integer> list = new ArrayList<>();
                for (UpdateCategoryChilrenDto child : children) {
                    child.setId(updateCategoryBo.getId());
                }
                /*marketDao.updateInnerCaregory(list, updateCategoryBo.getPid());*/
                marketDao.updateInnerCaregory(children, updateCategoryBo.getPid());
                System.out.println(children);
            }
        } else {
            //一级变一级
            marketDao.updateOutCategory(updateCategoryBo);
/*            List<UpdateCategoryChilrenDto> children = updateCategoryBo.getChildren();
            ArrayList<Integer> list = new ArrayList<>();
            for (UpdateCategoryChilrenDto child : children) {
                list.add(child.getId());
            }
            marketDao.updateInnerCaregory(updateCategoryBo);*/
        }

    }

    /**
     * 获取快递公司信息
     *
     * @return
     */
    @Override
    public List<MarketChannelVo> getChannel() {
        return marketDao.getChannel();
    }

    @Override
    public void shipOrder(OrderShipBo orderShipBo) {
        marketDao.shipOrderMsg(orderShipBo);

        //更新订单数据
        MarketOrder marketOrder = new MarketOrder();
        marketOrder.setId(orderShipBo.getOrderId());
        marketOrder.setShipSn(orderShipBo.getShipSn());
        marketOrder.setShipChannel(orderShipBo.getShipChannel());
        marketOrder.setShipTime(new Date(System.currentTimeMillis()));
        marketOrder.setUpdateTime(new Date(System.currentTimeMillis()));
        wxOrderDao.updateOrderValues(marketOrder);
    }

    /**
     * 获取订单详细信息
     *
     * @param orderId
     * @return
     */
    @Override
    public MarketOrderDetailVo getOrderDetail(Integer orderId) {
        MarketOrderDetailVo marketOrderDetailVo = new MarketOrderDetailVo();
        //获取订单详情中订单信息
        MarketOrderVo order = marketDao.getOrderDetailByOrderId(orderId);

        //获取订单中商品详情
        List<MarketOrderGoodsD> orderGoods = marketDao.getOrderDetailGoods(orderId);

        //获取用户信息
        MarketOrderUserD user = marketDao.getOrderDetailUser(order.getUserId());
        //封装
        marketOrderDetailVo.setOrder(order);
        marketOrderDetailVo.setOrdergoods(orderGoods);
        marketOrderDetailVo.setUser(user);
        return marketOrderDetailVo;
    }

    /**
     * 订单管理——删除订单
     *
     * @param orderId
     */
    @Override
    public void deleteOrder(Integer orderId) {
        marketDao.deleteOrder(orderId);
    }
}

